@file:JvmName("ImplBridge")

package org.lc.httpcollector

import okhttp3.Authenticator
import org.lc.httpcollector.model.Response
import org.lc.httpcollector.model.Server
import org.lc.httpcollector.tool.*

val log = Collector::class.logger()

/**
 * 发送请求的实现
 */
var sendRequest: suspend (Server, String) -> Response = { s, u -> HttpUtil.sendAsync(s, u) }

/**
 * 保存文件的实现
 */
val saveFile: (Server, String, Response) -> Unit = FileUtil::saveDefaultFile

/**
 * 解析后续url的实现
 */
var parseNextUrls: (String?) -> List<String> = RedfishUtil::parseNextUrls

/**
 * 响应过滤，不记录指定错误的响应内容，例如method not support
 */
var responseFilter: (Server, String, Response) -> Boolean = RedfishUtil::accept

/**
 * 映射文件名，通常用来解决某些字符无法被当前OS文件系统接受的问题
 */
var mapPathName = { path: String -> path.replaceAll(blackFileNames, "_") }

/**
 * 服务器 映射 目录名
 * 可设置相对路径或绝对路径
 */
var mapServerName = { server: Server -> mapPathName(server.ip) }

/**
 * 保存文件后回调，可用于界面展示
 */
var afterSaveFile = { server: Server, url: String, response: Response ->
    log.info("save: [${server.ip}] $url")
}

/**
 * 鉴权实现
 */
var authFactory: (Server) -> Authenticator = { server: Server ->
    when {
        server.authType.equals("basic", true) -> BasicAuth(server)
        server.authType.equals("session", true) -> TODO()
        else -> throw NotImplementedError("不支持的协议：${server.authType}")
    }
}

/**
 * 创建okHttp客户端的工厂方法
 */
var clientFactory = HttpUtil::defaultClientFactory

/**
 * 请求工厂方法
 */
var requestFactory = HttpUtil::defaultRequestFactory

/**
 * 响应回调工厂方法
 */
var callableFactory = HttpUtil::defaultCallableFactory

var onCollectStarting: (Server) -> Unit = { server: Server ->
    collectTimeUse[server.ip] = TimeUse()
}

var onCollectFinish: (Server) -> Unit = { server: Server ->
    HttpUtil.closeClient(server)
    collectTimeUse.remove(server.ip)?.stop().apply {
        log.debug("采集{}完成, 耗时 {}", server.ip, this)
    }
}

private val collectTimeUse = mutableMapOf<String, TimeUse>()